<?php

/* Crops an image to the desired width and height.
 */
function make_thumbnail($image, $width, $height) {

	// Detect filetype
	if (preg_match('/jpg|jpeg/',$image)){
		//header('Content-Type: image/jpeg');
		$src = imagecreatefromjpeg($image);
	}
	if (preg_match('/png/',$image)){
		//header('Content-Type: image/png');
		$src = imagecreatefrompng($image);
	}
	
	// Get the size of the original image.
	list($src_width, $src_height) = getimagesize($image);
	
	$thumb = ImageCreateTrueColor($width,$height);
	
	imagecopyresampled($thumb, $src, 0, 0, 0, 0, $width, $height, $src_width, $src_height);
	
	return $thumb;
}

/* return the dominant category (useful when article is tagged with more than one category
 * $type can be 'text' or 'slug'
 */
function dominant_category($type) {
	// get all the categories for this page or article
	// if category has no parents (ex: post is marked as reviews and show reviews)
	// assume that the child category (show reviews) is the article type
	$category = get_the_category();

	
	// if tagged with other categories, first look for features category, and remove if found
	if(count($category) > 1) {
		foreach($category as $key => $value) {
			// remove the 'features' category
			if ($value->cat_name == 'features')
				unset($category[$key]);
		}
	}
	
	// then, if still more than 1 category, look for parent category, and remove if found
	if(count($category) > 1) {
		foreach($category as $key => $value) {
			// categories with no parent return a 0
			if (!($value->category_parent))
				unset($category[$key]);
		}
	}
	
	if($type == 'text') {
		if(is_category() || is_home())
			return single_cat_title('', false);
		else {
			$first = reset($category);
			return $first->cat_name;
		}
	}
	
	if($type == 'slug') {
		$first = reset($category);
		return $first->slug;
	}
}

function secs_to_mins($secs) {
	$mins = floor($secs / 60);
	$secs = $secs % 60;
	if ($secs <10)
		$secs = '0'.$secs;
	return "$mins:$secs";
}

/* removes non alphanumeric characters that can trip up last.fm
 * encodes clean string to be put in url (ex: 'test & string' becomes 'test+string')
 * regex from http://stackoverflow.com/questions/4973089/cleaning-text-scraped-from-webpage-with-php-regex
 */
function prep_search_string($string) {
	$string = preg_replace('/[^a-zA-Z0-9-\s\'\!\,\|\(\)\.\*\#\/\:]/', ' ', $string);
	$string = explode(' ', $string);
	foreach ($string as $key => $word) {
		if ($word == '' || $word[0] == '#') 
			unset($string[$key]);
	}
	$string = implode(' ', $string);
	return urlencode($string);
}

/* case insensitive explode
 * from: http://theserverpages.com/php/manual/en/function.explode.php#37563
 */
function explodei($separator, $string, $limit = false) { 
   $len = strlen($separator); 
   for ($i = 0; ; $i++) { 
       if (($pos = stripos($string, $separator)) === false || ($limit !== false && $i > $limit - 2)) { 
           $result[$i] = $string; 
           break; 
       } 
       $result[$i] = substr($string, 0, $pos); 
       $string = substr($string, $pos + $len); 
   } 
   return $result; 
} 

/* takes a standard show review title (ex: "Pretty Lights @ House of Blues 11.5.10")
 * splits title up into venue and artists and returns array of results
 * returns "artists" and "venue" keys, $venue is always a string and $artists is an array of the artists
 */
function get_show_info($show_review_title) {
	// split review title string by the '@' character, artists before, venue after
	$show_review_title = explode('@', $show_review_title);
	
	// go through initial artist string and check for multiple artists
	// by checking for "with" and "and" keywords
	$artists = trim($show_review_title[0]);
	// checks if artists string has keyword "with"
	// we want to check for this first since less band names can contain the word "and"
	// we don't want to take a valid band name (ex: "florence and the machine") and ruin it by splitting it
	// it's likely that an author, if reviewing a show of two artists, one of which has an "and", will
	// conjoin the artist names with "with" (same goes for "w/")
	// (ex: "florence and the machine WITH radiohead" rather than "florence and the machine AND radiohead")
	if(stristr($artists, ' with '))
		$artists = explodei(' with ', $artists);
	else if(stristr($artists, ' w/ '))
		$artists = explodei(' w/ ', $artists);
	else if(stristr($artists, ' and '))
		$artists = explodei(' and ', $artists);
	else
		$artists = array($artists);	
	
	// clean up artists strings
	foreach($artists as $key => $artist)
		$artists[$key] = trim($artist);
	
	// go through venue string and parse out date and whitespace
	$venue = trim($show_review_title[1]);
	// remove all non letters from venue name (namely the date)
	$venue = preg_replace('/[^a-z-\s]/i', '', $venue);
	
	return array('artists' => $artists, 'venue' => $venue);
}

/* helper to get_interview_artist() - must be performed for each condition. performs the actual
 * extraction
 */
function extract_artist_name($string, $pre_wrapper) {
	$artist = stristr($string, $pre_wrapper);
	$artist = substr($artist, strlen($pre_wrapper));
	$artist = preg_replace('/[^a-z-\s]/i', '', $artist);
	return $artist;
}

/* much like get_show_info - must extract artist name from interview title to pass to artist object
 * enables interview articles to display last.fm mini bios of the interviewed artist 
 * 
 * have to parse the band name out of the title
 *
 * common band name wrappers:
 *  - [name]: A Q&A
 *  - A Q&A WITH: [name]
 *  - A Q&A WITH [name]
 *  - Q&A WITH: [name]
 *  - Q&A WITH [name]
 *  - AN INTERVIEW WITH: [name]
 *  - AN INTERVIEW WITH [name]
 *  - [name] INTERVIEW
 *  - [name]: INTERVIEW
 *  - JUST A TASTE OF... [name]
 */
function get_interview_artist($interview_title) {
	// check first for broad category of title wrapper, then refine as we figure out in which
	// wrapper it's contained
	/*
	if (stristr($interview_title, 'q&a')) {
		// don't check for colon - will be filtered out by regex that removes non-letter characters
		if (stristr($interview_title, 'q&a with'))
			return extract_artist_name($interview_title, 'q&a with');
		// this one returns the part of the string before the search term
		// assumes format [name]: A Q&A
		// only works in php 5.3.0+
		if (stristr($interview_title, 'a q&a', true)) {
			$artist = stristr($interview_title, 'a q&a', true);
			$artist = preg_replace('/[^a-z-\s]/i', '', $artist);
			return $artist;
		}
	}
	*/
	// needle "q&a" not working because of ampersand, this is an improvisation
	// just removes the "q&" in "q&a with"
	if (stristr($interview_title, 'a with'))
		return extract_artist_name($interview_title, 'a with');
	// this one returns the part of the string before the search term
	// assumes format [name]: A Q&A - uses "a q" of "a q&a" to avoid ampersand issue
	// only works in php 5.3.0+
	if (stristr($interview_title, 'a q', true)) {
		$artist = stristr($interview_title, 'a q', true);
		$artist = preg_replace('/[^a-z-\s]/i', '', $artist);
		return $artist;
	}
	if (stristr($interview_title, 'interview')) {
		// don't check for colon - will be filtered out by regex that removes non-letter characters
		if (stristr($interview_title, 'interview with'))
			return extract_artist_name($interview_title, 'interview with');
		// this one returns the part of the string before the search term
		// assumes format [name] INTERVIEW
		// only works in php 5.3.0+
		if (stristr($interview_title, 'interview', true)) {
			$artist = stristr($interview_title, 'interview', true);
			$artist = preg_replace('/[^a-z-\s]/i', '', $artist);
			return $artist;
		}
	}
	// there are only two interviews of this wrapper format - so not checking for variations
	// don't check for ellipses - will be filtered out by regex that removes non-letter characters
	if (stristr($interview_title, 'just a taste of'))
		return extract_artist_name($interview_title, 'just a taste of');
}

/* display a custom preview based on the article's category (photo articles display photoreel)
 * replaces the_excerpt as well as echoing the article title. handles everything inside .post
 */
function category_preview() {
	$category = dominant_category('slug');
	
	switch($category) {
	
		case 'photos':
			// pass the photoset object the photoset url
			// expects the_content() to be photoset url (ex: http://www.flickr.com/photos/user/sets/999/)
			$photoset = new photoset(get_the_content());
			
			echo '<div class="twelvecol last">';
			echo '<h1>',
				 '<img src="'.get_bloginfo('template_directory').'/images/icons/'.$category.'.png" /> ',
				 '<a href="'.get_permalink().'">', the_title(), '</a>',
				 '</h1>';
			$photoset->render_preview();
			echo '</div>';
			
			break;
		case 'cd-reviews':
			echo '<div class="twocol">';
			echo '<a href="'.get_permalink().'">'; the_post_thumbnail('medium'); echo '</a>';
			echo '</div>';
			
			echo '<div class="tencol last">';
			echo '<h1>',
				 '<img src="'.get_bloginfo('template_directory').'/images/icons/'.$category.'.png" /> ',
				 '<a href="'.get_permalink().'">', the_title(), '</a>',
				 '</h1>';
			$custom_fields = get_post_custom();
			if ($custom_fields[rating])
				display_rating();
			the_excerpt();
			echo '</div>';
			
			break;
		case 'show-reviews':
			// parses the title to get the venu / artist(s) show info on last.fm
			$show_info = get_show_info(get_the_title());
			$venue = new venue($show_info['venue']);
					
			if ($venue->get_image()) {
				echo '<div class="twocol">';
				echo '<a href="'.get_permalink().'"><img src="'. $venue->get_image() .'" /></a>';
				echo '</div>';
				
				echo '<div class="tencol last">';
				echo '<h1>',
					 '<img src="'.get_bloginfo('template_directory').'/images/icons/'.$category.'.png" /> ',
					 '<a href="'.get_permalink().'">', the_title(), '</a>',
					 '</h1>';
				the_excerpt();
				echo '</div>';
			} else {
				echo '<div class="twocol">';
				echo '<a href="'.get_permalink().'">'; the_post_thumbnail('medium'); echo '</a>';
				echo '</div>';
				
				echo '<div class="tencol last">';
				echo '<h1>',
					 '<img src="'.get_bloginfo('template_directory').'/images/icons/'.$category.'.png" /> ',
					 '<a href="'.get_permalink().'">', the_title(), '</a>',
					 '</h1>';
				the_excerpt();
				echo '</div>';
			}
			
			break;
		case 'issues':
			echo '<div class="fourcol issue">';
			echo '<h1>',
				 '<img src="'.get_bloginfo('template_directory').'/images/icons/'.$category.'.png" /> ',
				 '<a href="'.get_permalink().'">', the_title(), '</a>',
				 '</h1>';
			echo '<a href="'.get_permalink().'">'; the_post_thumbnail('issue-thumb'); echo '</a>';
			echo '</div>';
			
			break;
		case 'blog':
			echo '<div class="twocol">';
			echo '<p class="date"><span>'.get_the_date('M d').'</span> '.get_the_date('Y').'</p>';
			echo '</div>';
		
			echo '<div class="tencol last">';
			echo '<h1>',
				 '<img src="'.get_bloginfo('template_directory').'/images/icons/'.$category.'.png" /> ',
				 '<a href="'.get_permalink().'">', the_title(), '</a>',
				 '</h1>';
			the_excerpt();
			echo '</div>';
		
			break;
		case 'features':
			echo '<div class="twocol">';
			echo '<a href="'.get_permalink().'">'; the_post_thumbnail('medium'); echo '</a>';
			echo '</div>';
		
			echo '<div class="tencol last">';
			echo '<h1><a href="'.get_permalink().'">', the_title(), '</a></h1>';
			the_excerpt();
			echo '</div>';
		
			break;
		default:
			echo '<div class="twocol">';
			echo '<a href="'.get_permalink().'">'; the_post_thumbnail('medium'); echo '</a>';
			echo '</div>';
		
			echo '<div class="tencol last">';
			echo '<h1>',
				 '<img src="'.get_bloginfo('template_directory').'/images/icons/'.$category.'.png" /> ',
				 '<a href="'.get_permalink().'">', the_title(), '</a>',
				 '</h1>';
			the_excerpt();
			echo '</div>';
	}
}

/* reduces copy pasta in all the different single post templates
 * simply displays the author / photographer etc.
 */
function display_credit() {
	$custom_fields = get_post_custom();
	
	$author = $custom_fields[author];
	if ($custom_fields[photographer])
		$photographer = $custom_fields[photographer];
	else
		$photographer = $custom_fields[photographers];
	
	if ($author[0])
		echo '<p>by '.$author[0].', published '.get_the_date('F jS Y').'</p>';
		
	if ($photographer[0])
		echo '<p>photos by '.$photographer[0].'</p>';
}

/* simply displays the rating of a cd review if the rating is
 * stored as a custom field
 * used on category and single views
 * assumes $custom_fields[rating] exists
 */
function display_rating() {

	$custom_fields = get_post_custom();
	
	$rating = strtolower($custom_fields[rating][0]);
	
	switch($rating) {
	
		case 'tasty':
			echo '<p id="rating">Moldy | Stale | Edible | Fresh | <em>Tasty!</em></p>';
			break;
		case 'fresh':
			echo '<p id="rating">Moldy | Stale | Edible | <em>Fresh</em> | Tasty!</p>';
			break;
		case 'edible':
			echo '<p id="rating">Moldy | Stale | <em>Edible</em> | Fresh | Tasty!</p>';
			break;
		case 'stale':
			echo '<p id="rating">Moldy | <em>Stale</em> | Edible | Fresh | Tasty!</p>';
			break;
		case 'moldy':
			echo '<p id="rating"><em>Moldy</em> | Stale | Edible | Fresh | Tasty!</p>';
			break;
		default:
			echo '<p id="rating">No rating yet :(</p>';
	}
}

/* backup function that fetches old grooveshark custom field
 * incase a cd review has no auto fetched data
 */
function display_old_player() {
	$custom_fields = get_post_custom();
	
	$player = $custom_fields[player];
	
	if ($player[0])
		echo '<div id="old_player">'.$player[0].'</div>';
}

/* accepts array of all author/post_id pairs and goes through them
 * and organizes them into a new array where each author shows up 
 * only once, with a sub array of all their post_ids
 * 
 * function expects wordpress functions to be available
 */
function sort_authors($all_author_pairs) {
	
	// init vars used for keeping track of previous authors and
	// new author array
	$prev_author_name = null;
	$prev_author_key = null;
	$new_authors = array();
	
	// sort through all authors and add each author name to the new authors
	// array only once. then if they show up again, add only the post_id 
	// to the already existing author in the new array
	// this produces a 2D array where each author has a subarray with all
	// their post_ids
	// the author is the array key, with the post_ids as a sub array
	foreach ($all_author_pairs as $key => $author_array) {
		$post_id = $author_array['post_id'];
		$author_name = $author_array['meta_value'];
		// remove anything in parenthesis 
		$author_name = trim(preg_replace("/\([^\)]+\)/", "", $author_name));
		// remove any html tags
		$author_name = trim(preg_replace("/\<[^\>]+\>/", "", $author_name));
							
		if ($author_name == $prev_author_name)
			$new_authors[$prev_author_name][] = $post_id;
		else {
			$new_authors[$author_name][] = $post_id;
			$prev_author_name = $author_name;
		}
	}
	
	// resets the array keys
	$new_authors = array_merge($new_authors);
	
	return $new_authors;
}

?>